package com.ruix.app.network.okhttp;

import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.Map;
import android.text.TextUtils;

import com.ruix.app.network.RequestManager;

/**
 * Created by hadexs on 2017/4/12.
 */

public class BaseRequest {
    // JSON格式
    private static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");

    // 执行请求［执行在调用者线程］
    protected static Response execute(OkHttpClient client, Request request) throws IOException {
        return client.newCall(request).execute();// 执行在调用者线程
    }

    // 创建基础headerBuilder
    private static Request.Builder createRequestBuilder() {
        return new Request.Builder()//
                .headers(RequestManager.commonHeaders);
    }

    /**
     * 获取GetRequest
     *
     * @param url
     * @return
     */
    protected static Request getGetRequest(String url) {
        return createRequestBuilder().url(url).build();//
    }

    /**
     * 获取PostRequest－提交Json数据
     *
     * @param url
     * @param jsonContent
     * @return
     */
    protected static Request getPostJsonRequest(String url, String jsonContent) {
        RequestBody requestBody = RequestBody.create(JSON, jsonContent);
        return createRequestBuilder().url(url).post(requestBody).build();//
    }


    /**
     * 获取PostRequest－提交Form表单－数据源为：JsonObj
     *
     * @param url
     * @param formContentJsonObj
     * @return
     */
    protected static Request getPostFormRequest(String url, JSONObject formContentJsonObj) {
        RequestBody requestBody = getFormRequestBody(formContentJsonObj);
        return createRequestBuilder().url(url).post(requestBody).build();//
    }

    /**
     * 获取PostRequest－提交Form表单及文件－MultipartBody－数据源为：JsonObj
     *
     * @param url
     * @param formContentJsonObj
     * @return
     */
    protected static Request getPostFormRequest(String url, JSONObject formContentJsonObj, Map<String, String> files, String mediaType) {
        RequestBody requestBody = getMultipartBody(formContentJsonObj, files, mediaType);
        return createRequestBuilder().url(url).post(requestBody).build();//
    }


    /**
     * 构建FormBody－数据源为：JsonObj
     *
     * @param formContentJsonObj
     * @return
     */
    private static RequestBody getFormRequestBody(JSONObject formContentJsonObj) {
        if (formContentJsonObj == null || formContentJsonObj.length() == 0) {
            return null;
        }
        FormBody.Builder builder = new FormBody.Builder();
        Iterator keys = formContentJsonObj.keys();
        if (keys != null) {
            while (keys.hasNext()) {
                String key = (String) keys.next();
                if (!TextUtils.isEmpty(key)) {
                    String value = formContentJsonObj.optString(key);
                    builder.add(key, value);
                }
            }
        }
        // 返回构建的RequestBody
        return builder.build();
    }

    /**
     * 构建MultipartBody－提交Form表单及文件－数据源为：JsonObj
     *
     * @param formContentJsonObj
     * @return
     */
    private static RequestBody getMultipartBody(JSONObject formContentJsonObj, Map<String, String> files, String mediaType) {
        if (formContentJsonObj == null || formContentJsonObj.length() == 0) {
            return null;
        }
        MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);
        Iterator keys = formContentJsonObj.keys();
        if (keys != null) {
            while (keys.hasNext()) {
                String key = (String) keys.next();
                if (!TextUtils.isEmpty(key)) {
                    String value = formContentJsonObj.optString(key);
                    builder.addFormDataPart(key, value);
                }
            }
        }

        for (Map.Entry<String, String> entry : files.entrySet()) {
            String key = entry.getKey();
            String value = entry.getValue();
            if (key != null && value != null) {
                File file = new File(value);
                MediaType contentType = MediaType.parse("media/type");
                if (file != null && contentType != null) {
                    RequestBody fileBody = RequestBody.create(contentType, file);
                    builder.addFormDataPart(key, file.getName(), fileBody);
                }
            }
        }
        // 返回构建的RequestBody
        return builder.build();
    }
}